﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Diagnostics;
using DataPie.Core;

namespace NetworkAutoBak
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            gvData.CellMouseDown += new DataGridViewCellMouseEventHandler(gvData_CellMouseDown);
            if (!Directory.Exists(outFilePath))
            {
                Directory.CreateDirectory(outFilePath);
            }
        }

        protected void gvData_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    gvData.ClearSelection();
                    gvData.Rows[e.RowIndex].Selected = true;
                    gvData.CurrentCell = gvData.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    //contextMenuStrip_ListViewItemRightClick.Show（MousePosition.X， MousePosition.Y）; 
                }
            }
        }
        DataSet myDataSet = null;
        private void btnLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog df = new OpenFileDialog();
            df.Filter = "Excel(*.xls)|*.xls";
            string fileName = "";
            if (df.ShowDialog() == DialogResult.OK)
            {
                fileName = df.FileName;
                tbFileName.Text = df.FileName;

                string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + df.FileName + ";" + "Extended Properties=Excel 8.0;";
                OleDbConnection oleConnection = new OleDbConnection(strConnection);

                string strCommondText = " SELECT * FROM [Sheet1$]";
                oleConnection.Open();
                myDataSet = new DataSet();
                OleDbDataAdapter oleAdper = new OleDbDataAdapter(strCommondText, oleConnection);
                oleAdper.Fill(myDataSet, "BakInfo");

                oleConnection.Close();
                gvData.DataSource = myDataSet.Tables[0];
                CheckBakData();
            }

        }
        string outFilePath = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd");
        private void CheckBakData()
        {
            for (int i = 0; i < this.gvData.Columns.Count; i++)
            {
                this.gvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            pb.Maximum = myDataSet.Tables[0].Rows.Count;
            int value = 0;
            for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
            {

                DataRow row = myDataSet.Tables[0].Rows[i];
                gvData.Rows[i].ContextMenuStrip = this.cmsStartHere;
                string canBak = row["可备份"].ToString().Trim();
                if (canBak != "是")
                {
                    continue;
                }
                string id = row["序号"].ToString().Trim();
                string managerIp = row["管理IP"].ToString().Trim();
                string hostName = row["设备名称"].ToString().Trim();

                string isDyPassword = row["Token"].ToString().Trim();
                string userName = row["用户名"].ToString().Trim();
                string password = row["密码"].ToString().Trim();

                string vbsPath = row["备份脚本"].ToString().Trim();
                string bakFileName = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + hostName + "-" + DateTime.Now.ToString("yyyMMdd");
                bool bakSucc = CheckFileExist(bakFileName);
                if (bakSucc)
                {
                    gvData.Rows[i].Cells[2].Style.BackColor = Color.GreenYellow;
                    row["结果"] = "成功";
                    pb.Value = value++;
                    tlbText.Text = (value) + "/" + myDataSet.Tables[0].Rows.Count;
                }
            }
        }
        void StartBak(int index)
        {
            if (myDataSet == null)
            {
                MessageBox.Show("请先加载数据!");
                return;
            }
            if (string.IsNullOrWhiteSpace(tbUserName.Text))
            {
                MessageBox.Show("请输入用户名!");
                return;
            }


            //  Process.Start("explorer", outFilePath);
            pb.Maximum = myDataSet.Tables[0].Rows.Count;

            for (int i = index; i < myDataSet.Tables[0].Rows.Count; i++)
            {


                DataRow row = myDataSet.Tables[0].Rows[i];
                if (i > 7)
                {
                    gvData.FirstDisplayedScrollingRowIndex = i-7;
                }
                if (i > 0)
                {
                    gvData.Rows[i - 1].Selected = false;
                }
                gvData.Rows[i].Selected = true;
                string canBak = row["可备份"].ToString().Trim();
                if (canBak != "是")
                {
                    continue;
                }
                string id = row["序号"].ToString().Trim();
                string managerIp = row["管理IP"].ToString().Trim();
                string hostName = row["设备名称"].ToString().Trim();

                string isDyPassword = row["Token"].ToString().Trim();
                string userName = row["用户名"].ToString().Trim();
                string password = row["密码"].ToString().Trim();

                string vbsPath = row["备份脚本"].ToString().Trim();
                string interLogin = row["交互式登录"].ToString().Trim();
                string tip = row["提示信息"].ToString().Trim();
             
                if (!cbOverwrite.Checked)
                {
                    if (row["结果"].ToString() == "成功")
                    {
                        continue;
                    }
                }
                if (!string.IsNullOrWhiteSpace(tip))
                {
                    MessageBox.Show(tip);
                }
                tlbStatus.Text = "正在备份:" + id + "," + hostName + "," + managerIp + "!";


                if (isDyPassword == "是" )
                {

                    userName = tbUserName.Text;
                    if (interLogin != "是")
                    {
                        InputPassword ip = new InputPassword(userName, "请输入" + id + "," + hostName + "," + managerIp + "的密码", tbPin.Text);
                        DialogResult dr = ip.ShowDialog();
                        if (dr == DialogResult.Cancel)
                        {
                            break;
                        }
                        if (dr == DialogResult.Ignore)
                        {
                            continue;
                        }
                        password = ip.Pass;
                    }
                    else
                    {
                        password = tbPin.Text;
                    }
                }
                if (!File.Exists(vbsPath))
                {
                    MessageBox.Show("脚本文件不存在!" + vbsPath);
                    continue;
                }
                FileStream aFile = new FileStream(vbsPath, FileMode.Open);
                StreamReader sr = new StreamReader(aFile);
                string vbs = sr.ReadToEnd();
                sr.Close();


                vbs = vbs.Replace("#USERNAME", userName);

                vbs = vbs.Replace("#PASS", password);
                vbs = vbs.Replace("#IP", managerIp);
                vbs = vbs.Replace("#FILEPATH", "\"" + outFilePath + "\"");
                vbs = vbs.Replace("#FILENAME", outFilePath + "\\" + hostName);
                vbs = vbs.Replace("#HOSTNAME", hostName);
                vbs = vbs.Replace("#DATE", DateTime.Now.ToString("yyyyMMdd"));
                vbs = vbs.Replace("#FTPIP", "127.0.0.1");
                if (!Directory.Exists("tempsc"))
                {
                    Directory.CreateDirectory("tempsc");
                }

                if (File.Exists("tempsc\\temp" + vbsPath))
                {
                    File.Delete("tempsc\\temp" + vbsPath);
                }
                FileStream bFile = new FileStream("tempsc\\temp" + vbsPath, FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(bFile, Encoding.UTF8);


                // Write data to file.
                sw.Write(vbs);
                sw.Close();
                Process p = new Process();
                ProcessStartInfo ps = new ProcessStartInfo(Application.StartupPath + "\\SCRT\\SecureCRT.exe", "/SCRIPT " + Application.StartupPath + "\\tempsc\\temp" + vbsPath);
                p.StartInfo = ps;
                p.Start();
                p.WaitForExit();
                //检查备份文件是否成功
                string bakFileName = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + hostName + "-" + DateTime.Now.ToString("yyyMMdd");
                bool bakSucc = CheckFileExist(bakFileName);

                if (!bakSucc)
                {
                    row["结果"] = "失败";
                    gvData.Rows[i].Cells[2].Style.BackColor = Color.Red;
                    BakSelect bs = new BakSelect(id + "," + hostName + "," + managerIp + "备份失败!");
                    bs.ShowDialog();
                    if (bs.SelectBakProc == BakProc.Retry)
                    {
                        i--;
                    }
                    if (bs.SelectBakProc == BakProc.Skip)
                    {

                    }
                    if (bs.SelectBakProc == BakProc.Stop)
                    {
                        break;
                    }
                }
                else
                {
                    gvData.Rows[i].Cells[2].Style.BackColor = Color.GreenYellow;
                    row["结果"] = "成功";
                    tlbText.Text = (i + 1) + "/" + myDataSet.Tables[0].Rows.Count;
                    pb.Value = i + 1;
                }

            }
        }

        private void btnStartBak_Click(object sender, EventArgs e)
        {
            StartBak(0);
        }
        private bool CheckFileExist(string bakFileName)
        {
            bool bakSucc = false;
            string bakFileName1 = bakFileName + ".txt";
            string bakFileName2 = bakFileName + ".ucs";
            if (File.Exists(bakFileName1))
            {
                FileInfo fi = new FileInfo(bakFileName1);
                if (fi.Length > 10)
                {
                    bakSucc = true;

                }
            }
            if (File.Exists(bakFileName2))
            {
                FileInfo fi = new FileInfo(bakFileName2);
                if (fi.Length > 2000)
                {
                    bakSucc = true;

                }
            }
            return bakSucc;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (myDataSet == null)
            {
                MessageBox.Show("请先加载数据!");
                return;
            }
            string fileName = outFilePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "网络配置备份结果.xls";
            DataTableToExcel.SaveExcel(fileName, myDataSet.Tables[0], "备份结果");
            Process.Start("explorer", outFilePath);
            //     MessageBox.Show("导出成功!", "导出结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            Process.Start("explorer", outFilePath);
        }

        private void 从该项开始备份ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (gvData.SelectedRows.Count > 0)
            {
                StartBak(gvData.SelectedRows[0].Index);
            }
        }
    }
}
